package com.inspur.gs.sbssdl.sbwhgl.sbwhby.sbwhby.front.sbbysztree.voactions;

import com.inspur.edp.bff.api.manager.context.QueryContext;
import com.inspur.edp.bff.spi.action.query.AbstractQueryAction;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.cef.entity.dependenceTemp.Pagination;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.common.commonudt.pathhierarchyinfo.entity.IPathHierarchyInfo;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;

import java.util.*;

public class queryDataVOAction extends AbstractQueryAction {

    public queryDataVOAction(QueryContext context) {
        super(context);
    }


    private final IBqlExecuter bqlExecuter = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);

    private final ArrayList<IEntityData> result = new ArrayList<>();

    private int classSeq = 1;

    public int getClassSeqAndAdd() {
        return classSeq++;
    }

    /**
     * '设备大类':{
     * 'bh':【classSeq】,
     * 'seq': 【私有自增编号】
     * 'child': {
     * '设备小类':{
     * 'bh':【父级编号，取父级编号后父级编号+1】
     * 'seq':【私有自增编号】
     * child:{}
     * }
     * <p>
     * }
     * }
     * 在构建时，添加子类信息到result中
     * {
     * id: uuid,
     * name: '设备大类1',
     * TreeInfo:{
     * Path: 0001,
     * isDetail: false,
     * Layer: 1,
     * }
     * }
     */
    // 修改此处SQL以及字段定义
    private final String[] columnNames = {"sbdl", "sbxl", "bydj"};
    private final String queryBydj = "select sbdl,sbxl,bydj from SBSS_SBYW_SBBYSZ group by sbdl,sbxl,bydj";


    @Override
    public void execute() {

        bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);

        List<DynamicResultRow> classRow = bqlExecuter.executeSelectStatement(queryBydj, new ArrayList<>());
        Map<String, Map<String, Object>> parentTreeInfo = new HashMap<>();

        // 构建基础大类info
        for (DynamicResultRow row : classRow) {
            Map<String, Object> rowData = new HashMap<>();
            // 首层
            String name = row.get(columnNames[0]).toString();
            if (!parentTreeInfo.containsKey(name)) {
                rowData.put("name", name);
                rowData.put("bh", String.format("%04d", getClassSeqAndAdd()));
                rowData.put("layer", 1);
                rowData.put("seq", 1);
                rowData.put("child", new HashMap<String, Object>());
                parentTreeInfo.put(name, rowData);
            } else {
                rowData = parentTreeInfo.get(name);
            }
            // 循环
            for (int i = 1; i < columnNames.length; i++) {
                rowData = getMap(columnNames[i], row, rowData);
            }
        }

        parentTreeInfo.forEach((k, v) -> getTreeInfo(v));
        result.forEach(System.out::println);

        Pagination pageInfo = getQueryContext().getFilter().getPagination();
        pageInfo.setPageCount(result.size());
        pageInfo.setTotalCount(result.size());

        HashMap<String, ArrayList<IEntityData>> queryresult = new HashMap<>();
        queryresult.put("queryresult", result);
        getQueryContext().setQueryResult(result);
        setResult(queryresult);
    }

    public void getTreeInfo(Map<String, Object> treeInfo) {
        Map<String, Object> child = (Map<String, Object>) treeInfo.get("child");
        if (!child.isEmpty()) {
            int layer = ((int) treeInfo.get("layer"));
            String name = treeInfo.get("name").toString();
            child.forEach((k, v) -> {
                if (layer == 1) {
                    ((Map<String, Object>)v).put("className",name);
                }else if (layer == 2){
                    String className = treeInfo.get("className").toString();
                    ((Map<String, Object>)v).put("className",className);
                    ((Map<String, Object>)v).put("bydjname",name);
                }
                getTreeInfo((Map<String, Object>) v);
            });
            treeInfo.put("isDetail", false);
            toTree(treeInfo);
        } else {
            treeInfo.put("isDetail", true);
            toTree(treeInfo);
        }
    }



    private Map<String, Object> getMap(String columnName, DynamicResultRow row, Map<String, Object> mapInfo) {
        String name = row.get(columnName).toString();
        if (!((Map<String, Object>) mapInfo.get("child")).containsKey(name)) {
            int layer = (int) mapInfo.get("layer") + 1;
            int seq = (int) mapInfo.get("seq");
            String bh = mapInfo.get("bh").toString();

            Map<String, Object> data = new HashMap<>();
            data.put("name", name);
            data.put("bh", String.format("%s%04d", bh, seq));
            data.put("layer", layer);
            data.put("seq", 1);
            data.put("child", new HashMap<String, Object>());

            Map<String, Object> child = (Map<String, Object>) mapInfo.get("child");
            child.put(name, data);
            mapInfo.put("seq", seq + 1);
            return data;
        } else {
            return (Map<String, Object>) ((Map<String, Object>) mapInfo.get("child")).get(name);
        }
    }


    private void toTree(Map<String, Object> mapinfo) {
        IEntityData vo = getContext().createData();
        vo.setID(UUID.randomUUID().toString());
        vo.setValue("name", mapinfo.get("name"));
        vo.setValue("className", mapinfo.get("className"));
        vo.setValue("bydjname", mapinfo.get("bydjname"));

        IPathHierarchyInfo treeInfo = (IPathHierarchyInfo) vo.getValue("TreeInfo");
        int layer = (int) mapinfo.get("layer");
        boolean isDetail = (boolean) mapinfo.get("isDetail");

        treeInfo.setIsDetail(isDetail);
        treeInfo.setLayer(layer);
        treeInfo.setPath(mapinfo.get("bh").toString());

        result.add(vo);
    }
}
